# views.py

import pdb

from django.contrib.auth.models import UserManager, User
from django.forms.formsets import formset_factory
from django.shortcuts import render_to_response

from psd.register.forms import PersonForm, RegRecordForm
from psd.register.models import Person, RegRecord, LOCATIONS

event = 'macaw1'

def sign_up_indiv(request):
    ## These aren't used below at the moment, but leaving them
    ## here for reference. -- aym
    person_fields = ['first_name', 'last_name', 'gender', 'age', 'seeking_primary', 'kinky',
                     'seek_gender', 'seek_age_min', 'seek_age_max', 'seek_kinkiness']
    reg_fields = ['nickname', 'email', 'add_to_mailings', 'seek_groups', 'groups_match_all',
                  'friend_dates', 'referred_by', 'pals', 'location', 'wants_childcare',
                  'children', 'comments', 'event', 'people']

    if request.method == 'POST':
        pform = PersonForm(request.POST)
        rform = RegRecordForm(request.POST)
        if pform.is_valid() and rform.is_valid():
            pcd = pform.cleaned_data
            pcd['gender'] = ','.join(pcd['gender'])
            pcd['seek_gender'] = ','.join(pcd['seek_gender'])
            p = Person(**pcd)
            p.save()
            
            rcd = rform.cleaned_data
            set_hidden_reg_fields(rcd)
            rcd['location'] = ','.join(rcd['location'])
            r = RegRecord(**rcd)
            r.save()
            r.people.add(p)
            r.save()
            add_group(r)
            return render_to_response('payment.html', {'reg': r})
        else:
            return render_to_response('error.html', {'pform': pform, 'rform': rform})
    else:
        pform = PersonForm(initial={'seek_kinkiness': 'EI'})
        rform = RegRecordForm()
    return render_to_response('registerIndiv.html', {'pform': pform, 'rform': rform})

user_welcome_template = """Dear %s,

You are registered!

We look forward to seeing you at the event on Monday, May 24th, 7:30-11:00pm at the Blue Macaw in San Francisco.  Remember that you absolutely need to be there by 7pm if you want to play.  Registration and pre-event socializing starts at 6:30pm.

Your ID Code is %s.  Don't lose it!

If you have received multiple of these emails, please let us know so we can make sure you are not double-registered.  If you want to change your registration, then register again and make a note to that effect in the comments box at the bottom of the form (e.g., "I previously registered as LM231.  Please delete the old record").

One last note: soon (we hope) you will be able to log in to our website and check out and change your profile.  When this happens you will need the following password: %s. 

- The PSD Tech Folks
info@polyspeeddating.com
http://www.polyspeeddating.com
"""

def psdid_stamp_user(p):
    id = mk_person_id(p)
    p.psdid = id
    p.save()

def add_group(g):
    members = g.people.all()

    for p in members:
        psdid_stamp_user(p)
    if len(members) == 1:
        g.psdid = members[0].psdid
    else:
        id = mk_group_id(g)
        g.psdid = id
    ## You can call email_user with args (subject, message, sender).
    ## If you leave out the sender, like here, it fills in the
    ## DEFAULT_FROM_EMAIL in settings.py.
    pw = UserManager().make_random_password()
    user = User.objects.create_user(g.psdid, g.email, pw)
    user.email_user("Registration confirmation for %s." % g.psdid, user_welcome_template % (g.nickname, g.psdid, pw))
    g.save()

def mk_person_id(p):
    bignum = 100 + p.id
    id = p.first_name[0] + p.last_name[0] + str(bignum)
    return id.upper()

def mk_group_id(g):
    bignum = 100 + g.id
    initials = [p.first_name[0] for p in g.people.all()]
    initials = ''.join(initials)
    id = initials + str(bignum) + 'G'
    return id.upper()

def sign_up_group(request):
    PersonFormset = formset_factory(PersonForm, extra=3, max_num=3)
    if request.method == 'POST':
        pformset = PersonFormset(request.POST)
        rform = RegRecordForm(request.POST)
        if pformset.is_valid() and rform.is_valid():
            rcd = rform.cleaned_data
            set_hidden_reg_fields(rcd)
            rcd['location'] = ','.join(rcd['location'])
            r = RegRecord(**rcd)
            r.save()
            for form in pformset.forms:
                if not form.cleaned_data:
                    continue
                pcd = form.cleaned_data
                pcd['gender'] = ','.join(pcd['gender'])
                pcd['seek_gender'] = ','.join(pcd['seek_gender'])
                p = Person(**pcd)
                p.save()
                r.people.add(p)
            if r.people.count() > 1:
                r.is_group = True
            r.save()
            add_group(r)
            return render_to_response('payment.html', {'reg': r})
        else:
            return render_to_response('error.html', {'pformset': pformset, 'rform': rform})
    else:
        pformset = PersonFormset()
        rform = RegRecordForm()
    return render_to_response('registerGroup.html', {'pformset': pformset, 'rform': rform})

def admin_checkboxes(request):
    PersonFormset = formset_factory(PersonForm)
    if request.method == 'POST':
        pformset = PersonFormset(request.POST)
        #if pformset.is_valid():
            

def set_hidden_reg_fields(rcd):
    for field in ['paid', 'cancelled', 'pending', 'here', 'stationary', 'is_group']:
        rcd[field] = False
    for field in ['geek_code', 'notes']:
        rcd[field] = ''
    for field in ['matches', 'oneway']:
        rcd[field] = 0
    rcd['event'] = event

def summarize(rr):
    is_group = len(rr.people.all()) > 1
    p = rr.people.all()[0]
    pn = "They" if is_group else pronoun(p.gender)
    copula = "are" if is_group else "is"
    if not rr.seek_groups:
        groupspec = "(not groups)"
    elif rr.groups_match_all:
        groupspec = "or groups (if all group members match)"
    else:
        groupspec = "or groups (if any group member matches)"
    block = "%s %s located %s, wanting to date people %s %s go on 'friend dates'. " % (
        pn,
        copula,
        long_place(rr.location),
        groupspec,
        "and" if rr.friend_dates else "but not",
    )
    more = []
    if rr.pals:
        more.append("%s should not be matched with these friend: %s." % (pn, rr.pals))
    if rr.wants_childcare:
        more.append("%s would like childcare." % pn)
    if rr.stationary:
        more.append("%s would like to stay stationary as much as possible during the event." % pn)

    if not is_group:
        name_is_redundant = rr.nickname.startswith(p.first_name)
        expanded_name = rr.nickname if name_is_redundant else "%s (%s)" % (p.first_name, rr.nickname)
        intro = summarize_person(p, expanded_name)
        return intro + '\n\n' +  block + ' '.join(more)
    else:
        return ('\n\n'.join(summarize_person(p) for p in rr.people.all()) + '\n\n' + 
                'Together they are called %s. ' % rr.nickname + block + ' '.join(more))
    
def summarize_person(p, name=None):
    long_kink = {'EI': '(who can be kinky or not)', 'K': 'who are kinky', 'NK': 'who are not kinky'}
    pn = pronoun(p.gender)
    return "%s is a %s-year-old %s (%skinky) looking for %s ages %s-%s %s. %s is %s looking for a new primary relationship." % (
            name if name is not None else p.first_name,
            p.age,
            long_gender(p.gender, plural=False),
            "not " if not p.kinky else "",
            long_gender(p.seek_gender, plural=True),
            p.seek_age_min,
            p.seek_age_max,
            long_kink[p.seek_kinkiness],
            pn,
            "potentially" if p.seeking_primary else "not")

def pronoun(g):
    if not isinstance(g, list):
        g = g.split(',')
    if 'Q' in g or ('M' in g and 'F' in g) or ('TM' in g and 'TF' in g): return "Zie"
    elif 'TM' in g: return "He"
    elif 'TF' in g: return "She"
    elif 'M' in g: return "He"
    elif 'F' in g: return "She"
    else: return "Zie"
    ## This last case should be impossible, but...

def long_gender(g, plural=False):
    names = {'M': ('man', 'men'),
             'F': ('woman', 'women'),
             'TM': ('transman', 'transmen'),
             'TF': ('transwoman', 'transwomen'),
             'Q': ('genderqueer', 'genderqueers')}
    if not isinstance(g, list):
        g = g.split(',')
    ## Use sets here in case order is somehow scrambled.
    if set(g) == set(names):
        return "people of any gender" if plural else "person of all genders"
    else:
        ## Because we are bad people, we will use the fact that
        ## you can treat bools as ints with True == 1 and False == 0.
        return '/'.join(names[x][plural] for x in g)

def long_place(p):
    placenames = dict(LOCATIONS)
    if not isinstance(p, list):
        p = p.split(',')
    return '/'.join( ("far away" if x == 'SE' else "in " + placenames[x]) for x in p)
